package yagwl.client.widget.internal;

import yagwl.client.widget.Spacer;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;

public class PageSizer extends Composite {
	private final HorizontalPanel rootHP = new HorizontalPanel();
	private final ListBox pageSizeLB = new ListBox();
	private int[] pageSizeOptions = { 25 };
	private int pageSizeOptionIndex = 0;

	public PageSizer() {
		initWidget(rootHP);
	}

	public void renderUI(final PageSizeChangeHandler pageSizeChangeHandler) {
    if (pageSizeOptionIndex >= pageSizeOptions.length)
      pageSizeOptionIndex = 0;
    if (pageSizeOptions.length == 1)
			return;

		for (int option : pageSizeOptions) {
			pageSizeLB.addItem("" + option);
		}
		pageSizeLB.setSelectedIndex(pageSizeOptionIndex);

		Label viewL = new Label("View: ");
		rootHP.add(viewL);
		rootHP.add(new Spacer(5, 1));
		rootHP.add(pageSizeLB);
		rootHP.setCellVerticalAlignment(viewL, HasVerticalAlignment.ALIGN_MIDDLE);
		pageSizeLB.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				pageSizeOptionIndex = pageSizeLB.getSelectedIndex();
				pageSizeChangeHandler.onChange();
			}
		});
	}
	
	public interface PageSizeChangeHandler {
		public void onChange();
	}

  /**
   * Sets page size options to be displayed
   */
  public void setPageSizeOptions(int[] pageSizeOptions) {
    if (pageSizeOptions == null || pageSizeOptions.length == 0)
      return;
    this.pageSizeOptions = pageSizeOptions;
  }

  /**
   * Sets which page size is to be used from the list of options
   */
  public void setPageSizeOptionIndex(int pageSizeOptionIndex) {
    if (pageSizeOptionIndex < 0)
      pageSizeOptionIndex = 0;
    this.pageSizeOptionIndex = pageSizeOptionIndex;
  }

  public int getPageSize() {
		return pageSizeOptions[pageSizeOptionIndex];
	}
  
  public boolean isRenderable() {
  	return pageSizeOptions.length > 1;
  }

}
